package com.stars.empoly.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.qmuiteam.qmui.kotlin.onClick
import com.stars.empoly.adapter.PopuBuyAdapter
import com.stars.empoly.base.MBActivity
import com.stars.empoly.config.ConfigRx
import com.stars.empoly.config.MIntentAction
import com.stars.empoly.databinding.ActivityPlaceOrderBinding
import com.stars.empoly.inte.ChoiceData
import com.stars.empoly.model.*
import com.stars.empoly.model.bean.PlatInfo
import com.stars.empoly.utils.PopuChoseDateUtils
import com.stars.empoly.utils.PopuRemarkUtils
import com.stars.empoly.vmodel.PlaceOrderVModel
import com.trailer.base.utils.B
import com.trailer.base.utils.UiSwitch

/**
 * 下单
 *on 2022/9/24
 */
class PlaceOrderActivity: MBActivity<PlaceOrderVModel, ActivityPlaceOrderBinding>() {

    var adapter:PopuBuyAdapter?=null
    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        var id=intent.extras?.getString("id")
        if(id=="-1"){//列表再来一单  --弃用
            var data=intent.extras?.getString("bean")
            val bean: OrderList = Gson().fromJson(data, OrderList::class.java)
            vm.technicianId =bean.technicianId

            setAgainData(bean)

            vm.bean.observe(this){

                val choseList =ArrayList<ServiceList.ContentBean>()
                for(ss in bean.serviceInfo){
                    for(k in it.content){
                        if(ss.serviceId==k.id){
                            k.choseNumber=ss.number
                            choseList.add(k)
                        }
                    }
                }
                //设置数据
                //设置adapter
                adapter = PopuBuyAdapter(object : ChoiceData {
                    override fun onRestuse(id: String?) {
                        //计算总额
                        var money: Double = 0.0
                        for (item in choseList) {
                            money += item.price.toDouble() * item.choseNumber.toInt()
                        }

                        vm.serverFee = "" + money
                        vm.setSum()

                    }

                })
                binding.recyclerView.adapter = adapter
                adapter?.addData(choseList)

                //设置金额
                var money: Double = 0.0
                for (item in choseList) {
                    money += item.price.toDouble() * item.choseNumber.toInt()
                }
                vm.serverFee = "" + money
                vm.setSum()

            }


        }else if(id=="-2"){//详情里的再来一单

            var beanId=intent.extras?.getString("beanId")
            vm.getOrderInfo(beanId)

            vm.orderBean.observe(this){
                vm.technicianId =it.technicianId
                setAaginDateTo(it)
            }

            vm.bean.observe(this){

                val choseList =ArrayList<ServiceList.ContentBean>()
                for(ss in vm.orderBean.value!!.serviceInfo){
                    for(k in it.content){
                        if(ss.serviceId==k.id){
                            k.choseNumber=ss.number
                            choseList.add(k)
                        }
                    }
                }
                //设置数据
                //设置adapter
                adapter = PopuBuyAdapter(object : ChoiceData {
                    override fun onRestuse(id: String?) {
                        //计算总额
                        var money: Double = 0.0
                        for (item in choseList) {
                            money += item.price.toDouble() * item.choseNumber.toInt()
                        }

                        vm.serverFee = "" + money
                        vm.setSum()

                    }

                })
                binding.recyclerView.adapter = adapter
                adapter?.addData(choseList)

                //设置金额
                var money: Double = 0.0
                for (item in choseList) {
                    money += item.price.toDouble() * item.choseNumber.toInt()
                }
                vm.serverFee = "" + money
                vm.setSum()

            }



        } else {
            vm.technicianId = intent.extras?.getString("id")
            vm.name.value = intent.extras?.getString("name")
            var data = intent.extras?.getString("list")
            val list: List<ServiceList.ContentBean> =
                Gson().fromJson(data, object : TypeToken<List<ServiceList.ContentBean>>() {}.type)

            //设置adapter
            adapter = PopuBuyAdapter(object : ChoiceData {
                override fun onRestuse(id: String?) {
                    //计算总额
                    var money: Double = 0.0
                    for (item in list) {
                        money += item.price.toDouble() * item.choseNumber.toInt()
                    }

                    vm.serverFee = "" + money
                    vm.setSum()

                }

            })
            binding.recyclerView.adapter = adapter
            adapter?.addData(list)

            //设置金额
            var money: Double = 0.0
            for (item in list) {
                money += item.price.toDouble() * item.choseNumber.toInt()
            }
            vm.serverFee = "" + money
            vm.setSum()

            //获取默认地址
            vm.getDefaultAddress()

        }

        vm.dateList.observe(this){
            //去选择时间
            PopuChoseDateUtils.show(context(),it,binding.llTime,object :ChoiceData{
                override fun onRestuse(time: String?) {
                    vm.choseTime=time
                    binding.tvTime.text=time

                }

            })

        }



    }


    override fun onResume() {
        super.onResume()
        if(vm.isGetAddress){
            vm.getDefaultAddress()
        }

    }

    //列表再来一单
    fun setAgainData(bean:OrderList){

        //地址
        vm.addressId=bean.memberAddressId
        vm.realName.value=bean.realName
        vm.phone.value=bean.phone
        vm.detailsAddress.value=bean.address
        vm.isShowAddress.value=true
        //设置服务
        vm.getChoseServe(bean.technicianId)

        vm.name.value=bean.technicianName

//        vm.choseTime=bean.serviceTime
//        binding.tvTime.text=bean.serviceTime
        //出行方式
        //重新获取车费
        vm.getCarFee()
        //设置支付方式
        vm.setPayType(bean.payType)


    }


    fun setAaginDateTo(bean:UseOrderDetail){

        //地址
        vm.addressId=bean.addressId
        vm.realName.value=bean.realName
        vm.phone.value=bean.phone
        vm.detailsAddress.value=bean.address
        vm.isShowAddress.value=true
        //设置服务
        if(null!=bean.technicianId) {
            vm.getChoseServe(bean.technicianId)
        }

        vm.name.value=bean.technicianName
        //设置备注
        vm.remak=bean.remarks
        binding.tvMark.text = bean.remarks

//        vm.choseTime=bean.serviceTime
//        binding.tvTime.text=bean.serviceTime
        //出行方式
        //重新获取车费
        vm.getCarFee()

        //设置支付方式
        vm.setPayType(bean.payType.toInt())

    }

    override fun listeners() {
        super.listeners()
        binding.llTime.onClick {
            //选择时间
            vm.getDate()

        }
        //选择优惠卷
        binding.llCoupon.onClick {
            UiSwitch.bundleRes(this@PlaceOrderActivity, CouponActivity::class.java,
                B().putString("type","1").ok(),MIntentAction.REQUEST_CODE_TWO
            )
        }
        //备注
        binding.llMark.onClick {
            PopuRemarkUtils.show(context(),binding.llMark,object :ChoiceData{
                override fun onRestuse(content: String?) {

                    vm.remak=content
                    binding.tvMark.text = content

                }
            })

        }
        binding.llSubmit.onClick {
            var choseList=ArrayList<PlatInfo>()
            var list=adapter?.data as List<ServiceList.ContentBean>
            for(item in list){
                if(item.choseNumber!="0"){
                    choseList.add(PlatInfo(item.id,item.choseNumber))
                }
            }

            if(choseList.size==0){
                toast("请选择相关服务")
                return@onClick
            }
            if(vm.addressId.isNullOrEmpty()){
                toast("请选择地址")
                return@onClick
            }
            if(vm.choseTime.isNullOrEmpty()){
                toast("请选择服务时间")
                return@onClick
            }
            if(vm.payType.isNullOrEmpty()){
                toast("请选择支付方式")
                return@onClick
            }
            if(vm.payType=="2"){
                toast("请选择余额支付或者支付宝支付")
                return@onClick
            }

            vm.toSubmit(choseList)


        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == MIntentAction.REQUEST_CODE_ONE) {
            if(null!=data){
                var s=data.extras?.getString("bean")
                val bean: AddressList = Gson().fromJson(s, AddressList::class.java)
                //设置数据
                vm.addressId=bean.id
                vm.realName.value=bean.realName
                vm.phone.value=bean.phone
                vm.detailsAddress.value=bean.detailsAddress
                vm.isShowAddress.value=true
                //重新获取车费
                vm.getCarFee()


            }
        }

        if (requestCode == MIntentAction.REQUEST_CODE_TWO) {

            if(null!=data){

                var s=data.extras?.getString("bean")
                val bean: CouponsBean = Gson().fromJson(s, CouponsBean::class.java)
                //判断金额是否满足
              //  var fee=vm.serverFee!!.toDouble()+vm.fare!!.toDouble()

                var fee=vm.serverFee!!.toDouble()

                if(bean.useMinPrice.toDouble()<=fee.toDouble()){
                    vm.couponTips.value=bean.couponTitle
                    vm.useMinPrice=bean.useMinPrice
                    vm.couponFee=bean.couponPrice
                    vm.couponId=bean.id
                    vm.setSum()
                }else{
                    toast("优惠劵小于使用面额，不可用！")
                }


            }

        }
    }



    override fun vmClass(): Class<PlaceOrderVModel> {
        return PlaceOrderVModel::class.java
    }
    override fun binding(): ActivityPlaceOrderBinding {
        return ActivityPlaceOrderBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return "订单支付"
    }

    override val isRxbus: Boolean
        get() = true


    @Subscribe(tags = [Tag(ConfigRx.PAY_COMPLETE)])
    fun setPayComplete(type: String) {
        if (vm.payType != "1") {

           toast("支付完成")

            //刷新订单
            RxBus.get().post(ConfigRx.PLACE_ORDER, "")
            //跳转到订单详情
            UiSwitch.bundle(
                context(),
                ReceivedDetailsActivity::class.java,
                B().putString("id", vm.orderId).ok()
            )
           finish()


        }
    }

    @Subscribe(tags = [Tag(ConfigRx.PAY_ERROR)])
    fun setPayError(type: String) {
        if (vm.payType != "1") {


           toast("支付失败")

        }
    }


    @Subscribe(tags = [Tag(ConfigRx.DELETE_ADDRESS)])
    fun setDeleteAdress(type: String) {
        //删除下单地址
        //获取默认地址
        vm.getDefaultAddress()
    }






}
